import datetime
from os import path

from flask import render_template, Blueprint, g, session, abort
from sqlalchemy import func

from BookWorldWeb.forms import CommentForm
from BookWorldWeb.models import db, User, Post, Comment, Tag, tags

# 博客蓝图
blog_blueprint = Blueprint(
    'blog',
    __name__,
    template_folder=path.join(path.pardir, 'templates', 'blog'),
    url_prefix="/blog"
)


def sidebar_data():
    """
    获取侧边栏数据
    :return: 侧边栏数据
    """
    # 获取最新文章
    recent = Post.query.order_by(
        Post.publish_date.desc()
    ).limit(5).all()
    # 获取最常用标签
    top_tags = db.session.query(
        Tag, func.count(tags.c.post_id).label('total')
    ).join(
        tags
    ).group_by(Tag).order_by(db.text('Total DESC')).limit(5).all()

    return recent, top_tags


@blog_blueprint.before_request
def before_request():
    if 'user_id' in session:
        g.user = User.query.get(session['user_id'])


@blog_blueprint.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404


@blog_blueprint.route('/restricted')
def admin():
    if g.user is None:
        abort(404)
    return render_template('admin.html')


@blog_blueprint.route('/')
@blog_blueprint.route('/<int:page>')
def home(page=1):
    """
    首页
    :param page: 默认为1
    :return: 首页
    """
    posts = Post.query.order_by(
        Post.publish_date.desc()
    ).paginate(page, 10)
    recent, top_tags = sidebar_data()

    return render_template(
        'home.html',
        posts=posts,
        recent=recent,
        top_tags=top_tags
    )


@blog_blueprint.route('/tag/<string:tag_name>')
def tag(tag_name):
    """
    获取标签列表
    :param tag_name: 标签名称
    :return: 标签页
    """
    tag = Tag.query.filter_by(title=tag_name).first_or_404()
    posts = tag.posts.order_by(Post.publish_date.desc())
    recent, top_tags = sidebar_data()

    return render_template(
        'tag.html',
        tag=tag,
        posts=posts,
        recent=recent,
        top_tags=top_tags
    )


@blog_blueprint.route('/user/<string:username>')
def user(username):
    """
    获取用户
    :param username: 用户名
    :return: 用户页
    """
    user = User.query.filter_by(username=username).first_or_404()
    posts = user.posts.order_by(Post.publish_date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template(
        'user.html',
        user=user,
        posts=posts,
        recent=recent,
        top_tags=top_tags
    )


@blog_blueprint.route('/post/<int:post_id>', methods=('GET', 'POST'))
def post(post_id):
    """
    文章列表
    :param post_id: 文章ID
    :return: 文章页
    """
    form = CommentForm()
    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.post_id = post_id
        new_comment.date = datetime.datetime.now()
        db.session.add(new_comment)
        db.session.commit()
    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template(
        'post.html',
        post=post,
        tags=tags,
        comments=comments,
        recent=recent,
        top_tags=top_tags,
        form=form
    )
